import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import moment from 'moment';
import qs from 'qs';
import _ from 'lodash';

import { addTab, timeLimit } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import PageHeader from '@/components/PageHeader';

import {
  Row,
  Col,
  Card,
  Input,
  DatePicker,
  Select,
  Button,
  Table,
  message,
  Tooltip,
  Modal,
} from 'antd';

import { TableListData } from './data';
import '@ant-design/compatible/assets/index.css';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { Item } = Form;
const { info } = Modal;
const { pathname } = window.location;

const unix = moment(new Date()).unix();
const oneDay = 1000 * 60 * 60 * 24;
const start_date = moment(unix * 1000 - oneDay * 4).format('YYYY-MM-DD');
const end_date = moment(new Date().getTime() + oneDay).format('YYYY-MM-DD');

interface ChargeRecordsProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  consumptionList: TableListData;
  gardenList: any;
  partnersList: any;
  bizType: Object;
  deviceType: Object;
}

interface ChargeRecordsState {
  searchValues: any;
  pageNum: number;
  numPerPage: number | undefined;
  rowId: number;
}

@connect(({
  consumptionRecords: {
    consumptionList,
    gardenList,
    partnersList,
  },
  common: { INITINFO: { bizType, deviceType } },
  loading,
}: any) => ({
  consumptionList,
  gardenList,
  partnersList,
  bizType,
  deviceType,
  loading: loading.effects['consumptionRecords/fetch'],
}))

class ChargeRecordsElem extends Component<ChargeRecordsProps, ChargeRecordsState> {
  columns = [
    {
      title: '上级合作商',
      dataIndex: 'parent_name',
      width: 150,
      render: (text: any, record: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '合作商',
      dataIndex: 'fcs_name',
      width: 150,
      render: (text: any, record: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '小区名称',
      dataIndex: 'garden_name',
      width: 200,
      render: (text: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '设备类型',
      dataIndex: 'storage_type_desc',
      width: 100,
      render: (text: any) => (text || '--'),
    },
    {
      title: '设备编号',
      dataIndex: 'storage_code',
      width: 120,
      render: (text: any) => (text || '--'),
    },
    {
      title: '　运单编号',
      dataIndex: 'exp_code',
      width: 150,
    },
    {
      title: '消费总额',
      dataIndex: 'total_amount',
      width: 100,
    },
    {
      title: '箱格类型',
      dataIndex: 'cell_type_desc',
      width: 100,
    },
    {
      title: '短信费用',
      dataIndex: 'sms_amount',
      width: 100,
    },
    {
      title: '平台服务费',
      dataIndex: 'plat_service_amount',
      width: 100,
    },
    {
      title: '业务类型',
      dataIndex: 'biz_type_desc',
      width: 100,
    },
    {
      title: '消费时间',
      dataIndex: 'biz_time',
      width: 150,
    },
  ];

  state: ChargeRecordsState = {
    searchValues: {},
    pageNum: 1,
    numPerPage: 20,
    rowId: 0,
  }


  static getDerivedStateFromProps(nextProps: any, perState: any) {
    const { location: { search } } = nextProps;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { ...searchValues } = query;

    return {
      ...perState,
      searchValues,
      pageNum: searchValues.pageNum || 1,
      numPerPage: searchValues.numPerPage || 20,
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    this.fetchAction('partners', { name: '' });
    this.fetchAction('garden');

    this.fetchBizTypeList();
    this.fetchDeviceTypeList();

    const { consumptionList } = this.props;
    if (consumptionList?.list?.length) return;

    this.fetchAction('fetch', this.getQueryParams());
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageNum, numPerPage } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageNum !== prevState.pageNum
      || numPerPage !== prevState.numPerPage) {
      this.setFieldsValue();
      this.fetchAction('fetch', this.getQueryParams());
    }
  }

  handleRouter = (routePath: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '统计曲线',
      url: `${routePath}`,
    });
  }

  // 获取业务类型列表
  fetchBizTypeList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchBizType',
      payload: {},
    });
  }

  // 获取设备类型
  fetchDeviceTypeList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchDeviceType',
      payload: {},
    });
  }

  // 表单设置初始值
  setFieldsValue = () => {
    const {
      searchValues: {
        biz_start_time,
        biz_end_time,
        biz_type,
        exp_code,
        momentDate,
        storage_code,
        storage_type,
        ...others
      },
    } = this.state;

    const params = {
      biz_type,
      exp_code,
      momentDate,
      storage_code,
      storage_type,
    };

    if (biz_start_time) {
      params.momentDate = [moment(biz_start_time), moment(biz_end_time)];
    } else {
      params.momentDate = [moment(start_date), moment(end_date)];
    }

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue({
      ...params,
      garden: Number(others['garden.id']) || undefined,
      franchise: Number(others['franchise.id']) || undefined,
    });
  }

  // 查询
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      if (!values.storage_type && values.storage_code) {
        message.error('请先选择设备类型后再进行查询!');
        return;
      }

      const { franchise, garden, momentDate } = values;
      const { partnersList = [], gardenList = [] } = this.props;
      const franchiseItem = partnersList.filter((item: any) => item.id === franchise);
      const gardenItem = gardenList.filter((item: any) => item.id === garden);

      const { numPerPage } = this.state;
      const params = {
        ...values,
        'franchise.id': franchise || '',
        'franchise.name': franchiseItem[0]?.name || '',
        'garden.id': garden || '',
        'garden.name': gardenItem[0]?.name || '',
        biz_start_time: momentDate ? moment(momentDate[0]).format('YYYY-MM-DD HH:mm:ss') : '',
        biz_end_time: momentDate ? moment(momentDate[1]).format('YYYY-MM-DD HH:mm:ss') : '',
        pageNum: 1,
        numPerPage,
      };

      delete params.franchise;
      delete params.garden;
      delete params.momentDate;

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '消费明细',
        url: `${pathname}?${qs.stringify(params)}`,
        isTopMenu: true,
      });
    });
  }

  // 重置
  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const params = {
      biz_start_time: moment(start_date).format('YYYY-MM-DD HH:mm:ss'),
      biz_end_time: moment(end_date).format('YYYY-MM-DD HH:mm:ss'),
      pageNum: 1,
      numPerPage: 20,
    };
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '消费明细',
      url: `${pathname}?${qs.stringify(params)}`,
      isTopMenu: true,
    });
  }

  // 导出明细
  handleExport = () => {
    info({
      title: '报表正在导出，请稍后至新统计系统-报表管理中下载查看',
    });

    const params = {
      is_export: 1,
      ...this.getQueryParams(),
    };

    this.fetchAction('export', params);
  }

  // 切换页码
  handlePerPage = (pageNum: number, numPerPage: number) => {
    const { searchValues } = this.state;
    const new_searchValues = { ...searchValues, pageNum, numPerPage };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '消费明细',
      url: `${pathname}?${qs.stringify(new_searchValues)}`,
      isTopMenu: true,
    });
  }

  fetchAction = (typeName: string, payload = {}) => {
    const { dispatch } = this.props;
    dispatch({
      type: `consumptionRecords/${typeName}`,
      payload,
    });
  }


  // 获取参数
  getQueryParams = () => {
    const {
      searchValues: { ...params },
      pageNum,
      numPerPage,
    } = this.state;

    params.pageNum = pageNum;
    params.numPerPage = numPerPage;

    if (!params.biz_start_time) {
      params.biz_start_time = moment(start_date).format('YYYY-MM-DD HH:mm:ss');
    }
    if (!params.biz_end_time) {
      params.biz_end_time = moment(end_date).format('YYYY-MM-DD HH:mm:ss');
    }

    return params;
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  render() {
    const {
      pageNum,
      numPerPage,
    } = this.state;

    const {
      form: { getFieldDecorator },
      loading,
      consumptionList,
      partnersList = [],
      gardenList,
      bizType,
      deviceType,
    } = this.props;

    const pagination: object = consumptionList
      ? {
        total: consumptionList.count,
        pageSize: Number(numPerPage),
        current: Number(pageNum),
        onChange: this.handlePerPage,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${consumptionList.count || 0}条数据`,
        onShowSizeChange: this.handlePerPage,
        showQuickJumper: true,
      }
      : {};

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form
            hideRequiredMark
            onSubmit={this.handleSearch}
            className="tableListForm"
          >
            <Row gutter={12}>
              <Col md={12} sm={24}>
                <Item label="起止日期" colon={false}>
                  {getFieldDecorator('momentDate', ({
                    initialValue: [
                      moment(start_date),
                      moment(end_date),
                    ],
                  }))(
                    <RangePicker
                      showTime={{ format: 'HH:mm:ss' }}
                      disabledDate={timeLimit}
                      format="YYYY-MM-DD"
                      style={{ width: '100%' }}
                    />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　合作商" colon={false}>
                  {getFieldDecorator('franchise')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {partnersList.map((item: any) => (
                        item.status === 1
                        && <Option value={item.id} key={item.id}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　运单号" colon={false}>
                  {getFieldDecorator('exp_code')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="　　小区" colon={false}>
                  {getFieldDecorator('garden')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {gardenList.map((item: any) => (
                        <Option value={item.id} key={item.id}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="设备类型" colon={false}>
                  {getFieldDecorator('storage_type')(
                    <Select
                      allowClear
                      placeholder="请选择"
                    >
                      {Object.keys(deviceType).map((key: any) => (
                        <Option
                          key={key}
                          value={key}
                        >
                          {deviceType[key]}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="设备编号" colon={false}>
                  {getFieldDecorator('storage_code')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="箱格类型" colon={false}>
                  {getFieldDecorator('cell_type')(
                    <Select
                      allowClear
                      placeholder="请选择"
                    >
                      <Option value="0">全部</Option>
                      <Option value="10901">大箱</Option>
                      <Option value="10902">中箱</Option>
                      <Option value="10903">小箱</Option>
                      <Option value="10904">超小箱</Option>
                      <Option value="10905">大(宽)箱</Option>
                      <Option value="10906">中(宽)箱</Option>
                      <Option value="10907">小(宽)箱</Option>
                      <Option value="10908">超小(宽)箱</Option>
                      <Option value="10909">文件箱</Option>
                      <Option value="10910">文件(宽)箱</Option>
                      <Option value="10911">超大箱</Option>
                      <Option value="10912">超大(宽)箱</Option>
                    </Select>,
                  )}
                </Item>
              </Col>

            </Row>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="业务类型" colon={false}>
                  {getFieldDecorator('biz_type')(
                    <Select
                      allowClear
                      placeholder="请选择"
                    >
                      {Object.keys(bizType).map((key: any) => (
                        <Option
                          key={key}
                          value={key}
                        >
                          {bizType[key]}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={12} sm={24} />
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    className="addButton smallButton marginL16"
                    type="primary"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>
        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={() => this.handleRouter('/partner/rechargeMoney/list/detail')}
            >
              统计曲线
            </Button>
            <Tooltip title={consumptionList.count > 6000 ? ' 导出明细最多导出6000条' : ''}>
              <Button
                disabled={consumptionList.count > 6000}
                type="primary"
                size="small"
                className="smallButton"
                onClick={this.handleExport}
              >
                导出明细
              </Button>
            </Tooltip>
          </div>
          <Table
            rowKey="id"
            className="statementTable tableHeight60"
            loading={loading}
            columns={this.columns}
            dataSource={consumptionList.list}
            pagination={pagination}
            scroll={{ x: 1600 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
      </Fragment>
    );
  }
}

export default Form.create()(ChargeRecordsElem);
